import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import { Button, message } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import type { CreateUserProps } from '../DyCps/components/CreateUserDrawer';
import { createDyCpsChannel, followDyOrder, saveFlowOrders } from './service';
import { useModel } from '@umijs/max';
import UpdateFormDy from './components/UpdateFormDy';
import CreateUserDrawer from './components/CreateUserDrawer';
import moment from 'moment';
import buildQueryString from '@/utils/buildQueryString';
import { fetchChannelUser } from '../DyCps/service';

const handleUpdateOrders = async (selectedRows: any) => {
  const hide = message.loading('正在更新');
  try {
    const rsp = await saveFlowOrders({ ...selectedRows });
    if(rsp.data.upType === "view") {
      if(rsp.data.url === "true") {
        message.success('跟单成功');
      } else {
        message.error('跟单失败');
      }
    } else{
      window.open(rsp.data.url);
    }
    // 
    hide();
    
    return true;
  } catch (error) {
    hide();
    message.error('跟单失败');
    return false;
  }
};
const handleCreateChannel = async (selectedRows: any) => {
  const hide = message.loading('正在更新');
  try {
    await createDyCpsChannel({ ...selectedRows });
    hide();
    message.success('更新成功');
    return true;
  } catch (error) {
    hide();
    message.error('更新失败');
    return false;
  }
};
const valueEnum = {
  1: {
    text: '已跟单',
    status: 'Success',
  },
  0: {
    text: '未跟单',
    status: 'Error',
  }
};
const valueFollowEnum = {
  1: {
    text: '完全跟单',
    status: 'Success',
  },
  0: {
    text: '项目与商品不统一',
    status: 'Error',
  }
};
const orderStatuses = [
  {
    label: '创建',
    value: 0,
  },
  {
    label: '支付',
    value: 10,
  },
  {
    label: '退款',
    value: 20,
  },
  {
    label: '部分退款',
    value: 21,
  },
  {
    label: '结算',
    value: 30,
  },
  {
    label: '确认收货',
    value: 40,
  },
];
const TableList: React.FC = () => {
  const { initialState } = useModel('@@initialState');
  const { currentUser } = initialState || {};
  const [requestStatus] = useState(currentUser?.userInfo?.role!='super')
  const [channelStatus] = useState(currentUser?.userInfo?.role==='normal')
  const actionRef = useRef<ActionType>();
  const [dateRange, setDateRange] = useState<any>();
  const [updateOrdersVisible, handleUpdateOrdersVisible] = useState<boolean>(false);
  const [createChannelVisible, handleCreateChannelVisible] = useState<boolean>(false);
  const [currentOrderRow, setCurrentOrderRow] = useState<CreateUserProps>();
  console.log(initialState);
  /**
   * @en-US International configuration
   * @zh-CN 国际化配置
   * */
  useEffect(() => {
    const startOfDay = new Date(new Date());
    startOfDay.setHours(0, 0, 0, 0);
    const endOfDay = new Date(new Date).setHours(23,59,59,0);
    setDateRange([startOfDay, endOfDay]);
  }, []);
  const columns: ProColumns<any>[] = [
   
    {
      title: '产品店铺',
      dataIndex: 'shopName',
      copyable: true,
    },
    {
      title: '订单号',
      dataIndex: 'oid',
      valueType: 'textarea',
      copyable: true,
    },
    {
      title: '支付金额',
      dataIndex: 'amount',
      hideInSearch: true,
      renderText: (text)=>{
        return text/100;
      },
    },
    {
      title: '渠道',
      dataIndex: 'channelId',
      valueType: "select",
      hideInSearch: requestStatus,
      hideInTable: channelStatus,
      request: async () => {
        const data = await fetchChannelUser({});
        return data.data
      }
    },
    
    {
      title: '订单创建时间',
      dataIndex: 'createTime',
      valueType: 'dateTime',
      hideInSearch: true,
    },
    {
      title: '订单支付时间',
      dataIndex: 'payTime',
      valueType: 'dateTime',
      hideInSearch: true,
    },
    {
      title: '订单状态',
      dataIndex: 'orderStatus',
      valueType: 'select',

      request: async () => {
        return orderStatuses;
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      valueType: 'select',
      valueEnum,
    },
    {
      title: '详细跟单',
      dataIndex: 'followStatus',
      valueType: 'select',
      hideInSearch: true,
      hideInTable: !channelStatus,
      valueEnum: valueFollowEnum,
    },
    // {
    //   title: '入库时间',
    //   dataIndex: 'entryTime',
    //   valueType: 'dateTime',
    //   hideInSearch: true,
    // },
    {
      title: '后台佣金比例',
      dataIndex: 'rate',
      hideInTable: requestStatus,
      hideInSearch: true,
      renderText:(text)=>{
        return text/100 + "%";
      }
    },
    {
      title: '渠道佣金比例',
      dataIndex: 'proRate',
      hideInTable: requestStatus,
      hideInSearch: true,
      renderText:(text)=>{
        return text/100 + "%";
      }
    },
    {
      title: '佣金比例',
      dataIndex: 'superRate',
      hideInSearch: true,
      sorter: (a, b) => a.superRate - b.superRate,
      renderText:(text)=>{
        return text/100 + "%";
      }
    },
    {
      title: '订单支付时间',
      dataIndex: 'orderDate',
      valueType: 'dateRange',
      hideInForm: true,
      hideInTable: true,
      search: {
        transform: (value) => {
          return {
            startTime: value[0],
            endTime: value[1],
          };
        },
        fieldProps: {
          value: dateRange,
          onChange: (value: any) => {
            if (value && value.length === 2) {
              setDateRange(value);
            }
          },
        },
      },
    },
  ];

  return (
    <PageContainer>
      <ProTable<API.RuleListItem, API.PageParams>
        headerTitle={'全部店铺'}
        actionRef={actionRef}
        rowKey="key"
        toolBarRender={() => [
          initialState?.currentUser?.userInfo?.role == 'super' ? 
          <Button
            key="2"
            type="primary"
            onClick={() => {
              handleCreateChannelVisible(true);
            }}
          >
            创建渠道
          </Button> : '',
          initialState?.currentUser?.userInfo?.role == 'super' || initialState?.currentUser?.userInfo?.role == 'admin' ? <Button
            key="2"
            type="primary"
            onClick={() => {
              handleUpdateOrdersVisible(true);
            }}
          >
            跟单
          </Button> : '',
        ]}
        search={{
          defaultCollapsed: false,
          labelWidth: 100,
          optionRender: ({ searchText, resetText }, { form }) => {
            return [
              <Button
                key="reset"
                style={{ marginRight: '10px' }}
                onClick={() => {
                  actionRef?.current?.reset();
                }}
              >
                {resetText}
              </Button>,
              <Button key="search" type="primary" htmlType="submit" style={{ marginRight: '10px' }}>
                {searchText}
              </Button>,
              <Button
              key="export"
              type="primary"
              onClick={() => {
                const startTime = moment(new Date(dateRange[0])).format('YYYY-MM-DD HH:mm:ss');
                const endTime = moment(new Date(dateRange[1]).setHours(23,59,59,0)).format('YYYY-MM-DD HH:mm:ss');
                const fieldData = form.getFieldsValue();
                let params = {
                  startTime,
                  exportType: 'follow_user',
                  token: localStorage.getItem('token'),
                  endTime,
                  ...fieldData,
                };
              
                let str = buildQueryString(params);
                window.open('/api/exportDyFile' + str);
                console.log(str);
              }}
            >
              导出
            </Button> 
            ];
          },
        }}
        request={async (params: any) => {
          const defaultValues = columns.reduce((acc, column) => {
          if (column.fieldProps && column.fieldProps.value !== undefined) {
                acc[column.dataIndex] = column.fieldProps.value;
              }
              return acc;
          }, {});

          const startTime = moment(new Date(dateRange[0])).format('YYYY-MM-DD HH:mm:ss');
          const endTime = moment(new Date(dateRange[1]).setHours(23,59,59,0)).format('YYYY-MM-DD HH:mm:ss');
          // 将默认值合并到请求参数中
          const data = { ...params, ...defaultValues, startTime, endTime };
          const rsp = await followDyOrder(data,);
          if (rsp.code === 'SUCCESS') {
            return { ...rsp.data };
          }
        }}
        columns={columns}
      />
      <UpdateFormDy
        onSubmit={async (value) => {
          // console.log(value);
          // return;
          const success = await handleUpdateOrders({ ...value });
          if (success) {
            handleUpdateOrdersVisible(false);
            setCurrentOrderRow(undefined);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onUpdate={async (value) => {
          handleUpdateOrdersVisible(false);
          setCurrentOrderRow(undefined);
          if (actionRef.current) {
            actionRef.current.reload();
          }
          window.open(value)
        }}
        onCancel={() => {
          handleUpdateOrdersVisible(false);
          setCurrentOrderRow(undefined);
        }}
        updateModalVisible={updateOrdersVisible}
        values={currentOrderRow || {}}
        formType={0}
      />
      <CreateUserDrawer
        onSubmit={async (value) => {
          // return;
          const success = await handleCreateChannel({ ...value });
          if (success) {
            handleCreateChannelVisible(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => {
          handleCreateChannelVisible(false);
        }}
        updateModalVisible={createChannelVisible}
        values={{}}
        formType={0}
      />
    </PageContainer>
  );
};
export default TableList;
